package com.ra.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ra.pojo.RespPageBean;
import com.ra.pojo.Talk;
import com.ra.mapper.TalkMapper;
import com.ra.pojo.dto.ConditionDTO;
import com.ra.pojo.dto.TalkAdminDTO;
import com.ra.pojo.dto.TalkDTO;
import com.ra.pojo.dto.UserDetailsDTO;
import com.ra.service.ITalkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ra.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 今晚几点睡_Ada
 * @since 2023-03-09
 */
@Service
public class TalkServiceImpl extends ServiceImpl<TalkMapper, Talk> implements ITalkService {

    @Autowired
    private TalkMapper talkMapper;

    @Override
    public void saveOrUpdateTalk(TalkDTO talkDTO) {
        Talk talk = BeanCopyUtil.copyObject(talkDTO, Talk.class);
        UserDetailsDTO userDetailsDTO = (UserDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        talk.setUserId(userDetailsDTO.getUserInfoId());
        this.saveOrUpdate(talk);
    }

    @Override
    public void delTalks(List<Integer> talkIds) {
        talkMapper.deleteBatchIds(talkIds);
    }

    ///ok
    @Override
    public RespPageBean<TalkAdminDTO> listTalksAdmin(ConditionDTO conditionDTO) {
        PageHelper.startPage(conditionDTO.getCurrent(),conditionDTO.getSize());
        Page<TalkAdminDTO> page=talkMapper.listTalksAdmin(conditionDTO);
        List<TalkAdminDTO> result = page.getResult();
        result.forEach(item->{
            if (Objects.nonNull(item.getImages())) {
                item.setImgs(Arrays.asList(item.getImages().split(",")));
            }
        });
        return new RespPageBean<>(page.getTotal(),result);
    }


    //////////////////////////////////////////////////////////////////ok
    //保存说说时前台要求xxx.jpg,xxx.png 用,分割
    @Override
    public TalkAdminDTO getTalkAdminById(Integer talkId) {
        TalkAdminDTO talkAdminDTO = talkMapper.getTalkAdminById(talkId);
        if (Objects.nonNull(talkAdminDTO.getImages())) {
            talkAdminDTO.setImgs(Arrays.asList(talkAdminDTO.getImages().split(",")));
        }
        return talkAdminDTO;
    }

}
